package com.xujiang.myblog.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xujiang.common.ui.CPBaseActivity;
import com.xujiang.common.util.Callback;
import com.xujiang.common.util.ToolBarHelper;
import com.xujiang.myblog.MApplication;
import com.xujiang.myblog.MainActivity;
import com.xujiang.myblog.R;
import com.xujiang.myblog.listener.EmptyTextChangedListener;
import com.xujiang.myblog.model.AccessToken;
import com.xujiang.myblog.model.Data;
import com.xujiang.myblog.model.Login;
import com.xujiang.myblog.model.LoginResult;
import com.xujiang.myblog.model.PreferUser;
import com.xujiang.myblog.network.retrofit.MRetrifit;
import com.xujiang.myblog.tools.CPProgressHelper;
import com.xujiang.myblog.util.Callback4;
import com.xujiang.myblog.util.InputMethodUtils;
import com.xujiang.myblog.util.L;
import com.xujiang.myblog.util.UIUtils;
import com.xujiang.myblog.util.ValidateUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends CPBaseActivity {

    @BindView(R.id.reg_email)
    EditText regEmail;
    @BindView(R.id.reg_password)
    EditText regPassword;
    @BindView(R.id.reg_repeat_password)
    EditText regRepeatPassword;
    @BindView(R.id.btn_sub_register)
    Button btnSubRegister;
    @BindView(R.id.btn_register_to_login)
    TextView btnRegisterToLogin;
    private CPProgressHelper mProgressHelper;

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private ToolBarHelper toolBarHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initToolbar();
        mProgressHelper = CPProgressHelper.with(this);

        regEmail.addTextChangedListener(mEmptyTextChangedListener);
        regPassword.addTextChangedListener(mEmptyTextChangedListener);
        regRepeatPassword.addTextChangedListener(mEmptyTextChangedListener);
    }

    private void initToolbar() {
        initToolBar();
        setTitle("注册");
        // setToolBarleft(R.mipmap.me_c);
        setToolBarRight(R.mipmap.message_c);
        toolBarHelper = getToolBarHelper();
        toolBarHelper.setOnclicklister(new Callback.EmptyCallback<View>() {

            @Override
            public void onSuccess(View view) {
                switch (view.getId()) {
                    case R.id.m_toolbar_left:
                        L.getToast().showLog(RegisterActivity.this, "test");
                        break;

                    case R.id.m_toolbar_title:
                        L.getToast().showLog(RegisterActivity.this, "test");
                        break;

                    case R.id.m_toolbar_right:
                        L.getToast().showLog(RegisterActivity.this, "test");
                        break;

                }
            }
        });

    }

    EmptyTextChangedListener mEmptyTextChangedListener = new EmptyTextChangedListener(
            new Callback4.EmptyCallback<CharSequence>() {
                @Override
                public void onYes(CharSequence charSequence) {
                    checkSubmitEnabled();
                }

                @Override
                public void onNo(CharSequence charSequence) {
                    btnSubRegister.setEnabled(false);
                }
            });

    private void checkSubmitEnabled() {
        boolean email = !TextUtils.isEmpty(regEmail.getText());
        boolean pwd = !TextUtils.isEmpty(regPassword.getText());
        boolean rpwd = !TextUtils.isEmpty(regRepeatPassword.getText());
        if (email && pwd && rpwd) {
            btnSubRegister.setEnabled(true);
        }
    }

    @OnClick({ R.id.btn_sub_register, R.id.btn_register_to_login })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sub_register:
                String mail = regEmail.getText().toString();
                String pwd = regPassword.getText().toString();
                String rePwd = regRepeatPassword.getText().toString();
                try {
                    ValidateUtils.isBlank(mail, getString(R.string.valid_str_can_not_blank));
                    ValidateUtils.isEmail(mail, this.getString(R.string.valid_str_email_invalid));
                    ValidateUtils.lessLength(pwd, 6, this.getString(R.string.valid_str_pwd_longer_than_6));
                    ValidateUtils.greaterLength(pwd, 32, this.getString(R.string.valid_str_pwd_less_than_32));
                    ValidateUtils.isContainsLetterAndNumber(pwd,
                            getString(R.string.valid_str_pwd_must_letter_and_number));
                    ValidateUtils.lessLength(rePwd, 6, this.getString(R.string.valid_str_pwd_longer_than_6));
                    ValidateUtils.greaterLength(rePwd, 32, this.getString(R.string.valid_str_pwd_less_than_32));
                    ValidateUtils.isContainsLetterAndNumber(pwd,
                            getString(R.string.valid_str_pwd_must_letter_and_number));

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!rePwd.equals(pwd)) {
                    UIUtils.showToast(getApplicationContext(), this.getString(R.string.valid_str_pwd_not_matched));
                    return;
                }
                view.requestFocus(); //设置焦点
                //隐藏软输入
                InputMethodUtils.hideSoftInput(this);
                doRegister(mail, pwd);

                break;
            case R.id.btn_register_to_login:
                UIUtils.startActivity(RegisterActivity.this, LoginActivity.class);
                break;
        }
    }

    private void doRegister(String mail, String pwd) {
        String dev_token = MApplication.getmPushAgent().getRegistrationId();
        final Login loginEntity = new Login(getApplicationContext(), mail, pwd, dev_token);
        loginEntity.md5Password();

        MRetrifit.get()
                .register(loginEntity, this.<AccessToken<Data>>bindToLifecycle(),
                        new com.xujiang.myblog.util.Callback.EmptyCallback<AccessToken<Data>>() {
                            @Override
                            public void onPreExecute() {
                                mProgressHelper.visible();
                            }

                            @Override
                            public void onSuccess(AccessToken<Data> accessToken) {

                                L.i(TAG, accessToken.toString());
                                actionLogin(loginEntity);
                            }

                            @Override
                            public void onError(Exception e) {
                                super.onError(e);
                                mProgressHelper.gone();
                                L.getToast().e(TAG, getApplicationContext(), e);
                            }
                        });

    }

    private void actionLogin(Login loginEntity) {
        MRetrifit.get().login(getApplicationContext(),
                loginEntity, RegisterActivity.this.<AccessToken<LoginResult>>bindToLifecycle(),
                new com.xujiang.myblog.util.Callback.EmptyCallback<AccessToken<LoginResult>>() {

                    @Override
                    public void onSuccess(AccessToken<LoginResult> accessToken) {
                        super.onSuccess(accessToken);
                        PreferUser.get().setLogin(true);  //设置登陆标志为true
                        MainActivity.logInOut(getActivity());
                        finish();
                        mProgressHelper.gone();
                    }

                    @Override
                    public void onError(Exception e) {
                        super.onError(e);
                        mProgressHelper.gone();
                        //                                ServerError.error(TAG, getApplicationContext(), e);
                        e.printStackTrace();
                    }
                });
    }

}
